package com.swak.utils.filter;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

/**
 * 所有的 filter 都会执行， 且可以设置后置处理器，但是后置处理器不能对最终的结果产生影响
 * 
 * @author lifeng
 * @param <I>
 * @param <O>
 */
public abstract class AbstractFilter<I, O> implements Filter<I, O> {

	Filter<I, O> filter;

	@Override
	public CompletionStage<O> filter(I request) {
		CompletionStage<O> future = this.doFilter(request);
		if (future != null) {
			return future.thenCompose(res -> {
				return this.doNext(request);
			});
		}
		return this.doNext(request);
	}

	/**
	 * 执行下一个 handle
	 *
	 * @param request 需处理的数据
	 * @return 异步处理结果
	 */
	private CompletionStage<O> doNext(I request) {
		if (this.filter != null) {
			CompletionStage<O> nextFuture = filter.filter(request);
			nextFuture.whenComplete((v, e) -> this.postFilter(request, v, e));
			return nextFuture;
		}
		return CompletableFuture.completedFuture(null);
	}

	/**
	 * 子类需要实现的业务逻辑
	 *
	 * @param request 需处理的数据
	 * @return 异步处理结果
	 */
	protected abstract CompletionStage<O> doFilter(I request);

	/**
	 * 子类需要实现的业务逻辑
	 *
	 * @param request 需处理的数据
	 * @return 异步处理结果
	 */
	protected void postFilter(I request, O response, Throwable e) {
	}

	@Override
	public Filter<I, O> chain(Filter<I, O> next) {
		this.filter = next;
		return this.filter;
	}
}
